package com.fenghuajueli.module_user.vip

import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import androidx.activity.viewModels
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.distinctUntilChanged
import androidx.lifecycle.flowWithLifecycle
import androidx.lifecycle.lifecycleScope
import com.blankj.utilcode.util.ToastUtils
import com.fenghuajueli.libbasecoreui.constants.AppConfigInfo
import com.fenghuajueli.libbasecoreui.constants.EventBusConstants
import com.fenghuajueli.libbasecoreui.constants.PrivacyConstantsUtils
import com.fenghuajueli.libbasecoreui.data.entity.eventbus.EventEntity
import com.fenghuajueli.libbasecoreui.data.entity.goods.GoodsEntity
import com.fenghuajueli.libbasecoreui.ui.PrivacyWebActivity
import com.fenghuajueli.libbasecoreui.user.UserInfoUtils
import com.fenghuajueli.libbasecoreui.utils.CommonUtils
import com.fenghuajueli.libbasecoreui.viewmodel.BaseViewModel
import com.fenghuajueli.libbasecoreui.viewmodel.data.OtherCodeData
import com.fenghuajueli.module_user.activity.UserViewModelBaseActivity
import com.fenghuajueli.module_user.model.UserViewModel
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 * @Author: sz_ijj
 * @Date: 2024-01-08 15:49
 **/
abstract class BaseVipActivity : UserViewModelBaseActivity() {
    private val userViewModel by lazy { UserViewModel() }
    val viewModel by viewModels<VipViewModel>()

    override fun setBaseViewModel(): BaseViewModel = userViewModel

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        EventBus.getDefault().register(this)
        checkNotNullCurrentGoods {
            userViewModel.handlerZfbSubscribeResult(intent, this, it)
        }
        userViewModel.getGoodsList(this)
        initBaseData()
    }

    private fun initBaseData() {
        userViewModel.goodsList.observe(this) {
            viewModel.setGoodsList(it)
        }

        userViewModel.otherStatusData.observe(this) { otherCodeData ->
            if (otherCodeData.code == OtherCodeData.PAY_SUCCESS) {
                //用户信息刷新
                viewModel.updateUserInfo()
            }
        }

        userViewModel.payOrder.distinctUntilChanged().observe(this) { isResume ->
            if (isResume && userViewModel.isH5pay.value == true) {
                userViewModel.checkOrderPayActive(this, userViewModel.h5OrderId.getValue())
            }
        }

        lifecycleScope.launch {
            launch {
                viewModel.updateInfoEvent
                    .flowWithLifecycle(lifecycle, Lifecycle.State.CREATED)
                    .collect {
                        showLoadingDialog()
                        delay(1000)
                        checkNotNullCurrentGoods {
                            initUpload()
                            userViewModel.updateUserInfo(this@BaseVipActivity, it)
                        }
                    }
            }
        }
    }

    fun toPay() {
        val buttonUiState = viewModel.buttonUiState.value

        if (buttonUiState.subscribe && !buttonUiState.isCheck) {
            showToast("请先阅读并勾选同意协议")
            return
        }

        if (TextUtils.equals(buttonUiState.payChannel, AppConfigInfo.PAY_CHANNEL_ZFB)) {
            if (!CommonUtils.checkAliPayInstalled(this)) {
                showToast("请先安装支付宝客户端！")
                return
            }
        } else {
            if (!CommonUtils.isWeixinAvilible(this)) {
                showToast("请先安装微信客户端！")
                return
            }
        }
        if (UserInfoUtils.getInstance().isForeverVip()) {
            ToastUtils.showLong("您已是永久会员，无须再开通！")
        } else {
            checkNotNullCurrentGoods {
                userViewModel.checkIsSubscribeZfbActive(this, it, buttonUiState.payChannel)
            }
        }
    }

    fun toPrivacyWeb(type: PrivacyConstantsUtils.ProtocolType = PrivacyConstantsUtils.ProtocolType.BUY_PROTOCOL) {
        PrivacyWebActivity.start(this, type)
    }

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        checkNotNullCurrentGoods {
            userViewModel.handlerZfbSubscribeResult(intent, this, it)
        }
    }

    fun checkNotNullCurrentGoods(postEntity: (GoodsEntity) -> Unit) {
        viewModel.currentGood.value?.let {
            postEntity(it)
        }
    }

    override fun onResume() {
        super.onResume()
        if (userViewModel.isH5pay.value == true) {
            userViewModel.payOrder.value = true
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        hideLoadingDialog()
        EventBus.getDefault().unregister(this)
    }

    abstract fun initUpload()

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun event(eventBusEntity: EventEntity) {
        if (eventBusEntity.code == EventBusConstants.PAY_ERROR) {
            hideLoadingDialog()
        }
        if (eventBusEntity.code == EventBusConstants.PAY_SUCCESS) {
            //延迟一秒从后台获取信息
            viewModel.updateUserInfo()
        }
        if (eventBusEntity.code == EventBusConstants.LOGIN_SUCCESS) {
            //延迟一秒是否支付
//            toPay()
        }
    }
}